package com.zxc.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zxc.common.dto.RegisterDto;
import com.zxc.common.enums.LoginAndRegisterEnum;
import com.zxc.common.enums.NumberEnum;
import com.zxc.common.enums.ZxcCommonEnum;
import com.zxc.common.lang.Result;
import com.zxc.entity.User;
import com.zxc.mapper.UserMapper;
import com.zxc.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.util.RandomImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2020-05-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param registerDto 用户注册信息
     * @return 返回注册体
     */
    @Override
    @Transactional
    public Result register(RegisterDto registerDto) {
        Result result = new Result();
        result.setCode(ZxcCommonEnum.SUCCESS.getKey());
        result.setMsg(LoginAndRegisterEnum.REGISTER_SUCCESS.getValue());
        //1、校验信息是否合法。

        //1.1手机号是否已经注册
        if (baseMapper.countUserByPhoneNumber(registerDto.getPhoneNumber()) > NumberEnum.ZERO.getKey()) {
            result.setCode(LoginAndRegisterEnum.REGISTERED.getKey());
            result.setMsg(LoginAndRegisterEnum.REGISTERED.getValue());
            return result;
        }

        //2、加密密码，生成账户信息
        if (!registerDto.getPass().equals(registerDto.getCheckPass())) {
            result.setCode(ZxcCommonEnum.FAIL.getKey());
            result.setMsg(LoginAndRegisterEnum.REGISTER_PASS_INCONSISTENT.getValue());
            return result;
        }
        registerDto.setPass(SecureUtil.md5(registerDto.getPass()));
        //3、给用户设置随机个人图片
        registerDto.setAvatar(RandomImageUtil.getRandomImageUrl());

        //注册账号
        Integer userId = userMapper.register(registerDto);
        if (ObjectUtils.isEmpty(userId)) {
            result.setCode(LoginAndRegisterEnum.FAIL.getKey());
            result.setMsg(LoginAndRegisterEnum.REGISTER_FAIL.getValue());
            return result;
        }
        registerDto.setId(userId);
        result.setData(registerDto);
        return result;
    }
}